#include "stdafx.h"
#include "BulletFrameListener.h"


BulletFrameListener::BulletFrameListener(
	Ogre::SceneManager* sceneMgr, 
	Ogre::Vector3 &gravityVector,
	Ogre::AxisAlignedBox &bounds):mSceneMgr(sceneMgr)
{
		mMoveSpeed = 50;	// defined in ExampleFrameListener
 		mNumEntitiesInstanced = 0; // how many shapes are created
 		mSceneMgr = sceneMgr;
 		// Start Bullet
 		mWorld = new OgreBulletDynamics::DynamicsWorld(mSceneMgr, bounds, gravityVector);
 
 	        // add Debug info display tool
 		debugDrawer = new OgreBulletCollisions::DebugDrawer();
 		debugDrawer->setDrawWireframe(true);	// we want to see the Bullet containers
 
 		mWorld->setDebugDrawer(debugDrawer);
 		mWorld->setShowDebugShapes(true);		// enable it if you want to see the Bullet containers
 		SceneNode *node = mSceneMgr->getRootSceneNode()->createChildSceneNode("debugDrawer", Ogre::Vector3::ZERO);
 		node->attachObject(static_cast <SimpleRenderable *> (debugDrawer));
 
                // Define a floor plane mesh
 		Entity *ent;
                Plane p;
                p.normal = Vector3(0,1,0); p.d = 0;
                MeshManager::getSingleton().createPlane("FloorPlane", 
                                                        ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, 
                                                        p, 200000, 200000, 20, 20, true, 1, 9000, 9000, 
                                                        Vector3::UNIT_Z);
                // Create an entity (the floor)
                ent = mSceneMgr->createEntity("floor", "FloorPlane");
 		ent->setMaterialName("Examples/BumpyMetal");
                mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent);
 
 		// add collision detection to it
 		OgreBulletCollisions::CollisionShape *Shape;
 		Shape = new OgreBulletCollisions::StaticPlaneCollisionShape(Ogre::Vector3(0,1,0), 0); // (normal vector, distance)
 		// a body is needed for the shape
 		OgreBulletDynamics::RigidBody *defaultPlaneBody = new OgreBulletDynamics::RigidBody("BasePlane",
  												    mWorld);
 		defaultPlaneBody->setStaticShape(Shape, 0.1, 0.8);// (shape, restitution, friction)
 		// push the created objects to the deques
 		mShapes.push_back(Shape);
 		mBodies.push_back(defaultPlaneBody);

}


BulletFrameListener::~BulletFrameListener(void)
{
	// OgreBullet physic delete - RigidBodies
 		std::deque<OgreBulletDynamics::RigidBody *>::iterator itBody = mBodies.begin();
 		while (mBodies.end() != itBody)
 		{   
 			delete *itBody; 
 			++itBody;
 		}	
 		// OgreBullet physic delete - Shapes
 		std::deque<OgreBulletCollisions::CollisionShape *>::iterator itShape = mShapes.begin();
 		while (mShapes.end() != itShape)
 		{   
 			delete *itShape; 
 			++itShape;
 		}
 		mBodies.clear();
 		mShapes.clear();
 		delete mWorld->getDebugDrawer();
 		mWorld->setDebugDrawer(0);
 		delete mWorld;
}
